package cn.codeforfun.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义注销逻辑
 *
 * @author wangbin
 */
@Component
public class CustomLogoutHandler implements LogoutHandler {
    @Resource
    TokenStore tokenStore;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token;
        if (!ObjectUtils.isEmpty(request.getHeader("Authorization")) && request.getHeader("Authorization").contains("bearer ")) {
            token = request.getHeader("Authorization").split("bearer ")[1];
        } else if (!ObjectUtils.isEmpty(request.getParameter("token"))) {
            token = request.getParameter("token");
        } else if (!ObjectUtils.isEmpty(request.getParameter("access_token"))) {
            token = request.getParameter("access_token");
        } else {
            return;
        }
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null) {
            return;
        }
        if (accessToken.getRefreshToken() != null) {
            tokenStore.removeRefreshToken(accessToken.getRefreshToken());
        }
        tokenStore.removeAccessToken(accessToken);
    }
}
